/**
 * User: alesj
 * Date: 23.3.2006
 * Time: 15:42:03
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blade.reports;

import com.alesj.blade.data.Customer;
import com.alesj.blade.data.Request;
import com.alesj.blade.login.LoggedIn;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.jboss.seam.annotations.*;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelectionIndex;
import org.jboss.seam.ejb.SeamInterceptor;

import javax.ejb.Interceptors;
import javax.ejb.Stateful;
import javax.ejb.Remove;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;
import java.io.Serializable;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
@Name(value = "report")
@Stateful
@LoggedIn
@Interceptors(SeamInterceptor.class)
public class ReportAction implements Report, Serializable {

    @In(value = "currentUser", required = true)
    Customer customer;

    @PersistenceContext
    Session session;

    @DataModel
    List<Request> requests;

    @Out(value = "request", required = false)
    Request request;

    @DataModelSelectionIndex
    int index;

    @Begin(join = true)
    @Factory("requests")
    public String progress() {
        return execute(new Executor() {
            public void execute() {
                requests = new ArrayList<Request>(customer.getInprogressRequests());
            }
        });
    }

    @Begin(join = true)
    @Factory("requests")
    public String finished() {
        return execute(new Executor() {
            public void execute() {
                requests = new ArrayList<Request>(customer.getFinishedRequests());
            }
        });
    }

    @Begin(join = true)
    @Factory("requests")
    public String history() {
        return execute(new Executor() {
            public void execute() {
                requests = new ArrayList<Request>(customer.getHistoryRequests());
            }
        });
    }

    private String execute(Executor executor) {
        session.lock(customer, LockMode.NONE);
        executor.execute();
        return "reports";
    }

    private interface Executor {
        void execute();
    }

    public String detailRequest() {
        request = (Request)session.merge(requests.get(index));
        request.getFrames();
        return "reports";
    }

    @End
    public String reset() {
        return null;
    }

    @Destroy
    @Remove
    public void destroy() {
    }

}
